"""
@file: share_info.py
@author: yangsiting
@data: 2021/04/27
@desc:
"""

from flask import request, g
from libs.nestable_blueprint import NestableBlueprint
from flask_restful import Api, Resource
from libs.handler import default_error_handler
from models.share import ShareInfo
from models.user import UserProfile
from models.base import db
from libs.response import generate_response
from serializer.user import user_schema
from serializer.share import shareinfos_schema
from libs.error_code import FormValidateException, ArgsTypeException
from libs.authorize import create_token
from libs.authorize import auth

share_bp = NestableBlueprint('share_v1', __name__, url_prefix='share/')
api = Api(share_bp)

class Share_Info_View(Resource):
    # @auth.login_required
    def post(self):
        # 获取用户传过来的数据
        data = request.json
        # print(data)
        # 验证参数有效性
        # RequestParse: 验证参数类型 => 弱
        # wtforms：更灵活，参数类型、参数值... => 推荐！！
        # 构建表单 => 设置参数的要求 => data与表单绑定 => 验证数据有效性
            # 注意： form.email.data
        ShareInfo.create_share(user_profile_id=data['user_id'],
                           share_message=data['share_message'],
                           share_img=data['share_img'])
        # user = ShareInfo.query.filter_by().first()
        # result = user_schema.dump(user)
            # 返回结果
        return generate_response(data={'message':'发布成功'})

class  Query_share_View(Resource):

    def get(self):
        share_info = ShareInfo.query.all()
        infos = []
        share_infos = shareinfos_schema.dump(share_info)
        # print(share_infos)
        for i in share_infos:
            # print(i["user_profile_id"])
            userinfo = UserProfile.query.filter(UserProfile.user_profile_id==i['user_profile_id']).first()
            user_info = user_schema.dump(userinfo)
            # print(user_info)
            i.update(user_info)
            infos.append(i)
        # print(i
        return generate_response(data=infos)

api.add_resource(Query_share_View, 'queryinfo/')
api.add_resource(Share_Info_View,'addinfo/')